<template>
	<view class="content">
		<view class="row b-b">
			<text class="tit">联系人</text>
			<input class="input" type="text" v-model="addressData.name" placeholder="收货人姓名" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">手机号</text>
			<input class="input" type="number" v-model="addressData.mobile" placeholder="收货人手机号码" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">所属地区</text>
			<text class="input" @tap="openPicker">
				{{addressData.province}}{{addressData.city}}{{addressData.district}}
			</text>
			<text class="yticon icon-shouhuodizhi"></text>
		</view>

		<!-- 省市区选择 province city area初始省市区设置 show:是否显示  @changeClick：更改省市区事件 @sureSelectArea：确认事件 @hideShow：隐藏事件-->
		<cc-selectDity :province="province" :city="city" :area="area" :show="show" @changeClick="changeClick" @sureSelectArea="onsetCity"
		    @hideShow="onhideShow"></cc-selectDity>
		<view class="row b-b">
			<text class="tit">街道信息</text>
			<input class="input" type="text" v-model="addressData.address" placeholder="请输入街道信息" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">门牌号</text>
			<input class="input" type="text" v-model="addressData.houseNumber" placeholder="楼号、门牌" placeholder-class="placeholder" />
		</view>

		<view class="row default-row">
			<text class="tit">设为默认</text>
			<switch :checked="addressData.default" color="#ff633d" @change="switchChange" />
		</view>
		<button class="add-btn" @click="confirm">提交</button>
	</view>
</template>

<script>
import qqmap from '@/utils/qqmap-wx-jssdk.min.js';
const qqmapsdk = new qqmap({ key: 'KEDBZ-NJ7WJ-OOXFM-KGYWA-YSG4O-M5FT4' });
import { searchUserInfoById, updateUserInfo } from '../../utils/api.js';
export default {
	data() {
		return {
			region: ['浙江省', '杭州市', '余杭区'],
			 province:"浙江省",
			 city:"杭州市",
			area: "余杭区",
			show: false,
			// addressData: {
			//       default: false,
			//       addressName: "在地图选择",
			//       address: "",
			//       province: "",
			//       city: "",
			//       district: "",
			//       latitude: 0,
			//       name: "",
			//       mobile: "",
			//       longitude: 0,
			//       areaCode: "",
			//       houseNumber: "",
			//     },

			addressData: {
				default: false,
				address: '',
				province: '浙江省',
				city: '杭州市',
				district: '余杭区',
				latitude: 0,
				name: '',
				mobile: '',
				longitude: 0,
				order: 0,
				houseNumber: ''
			},

			addressList: [],
			manageType: '',
			ind: ''
		};
	},
	onLoad(option) {
		console.log(option);

		let title = '新增收货地址';
		if (option.type === 'edit') {
			title = '编辑收货地址';
			this.addressData = JSON.parse(option.data);
		}
		this.manageType = option.type;
		this.ind = option.ind;
		uni.setNavigationBarTitle({
			title
		});
	},
	onShow() {
		this.getuserInfo();
	},
	methods: {
		switchChange(e) {
			this.addressData.default = e.detail.value;
		},
		getuserInfo() {
			let data = {
				userId: uni.getStorageSync('userInfo').id
			};
			searchUserInfoById(data).then(res => {
				if (res.code == 200) {
					if (res.body.receiveAddressJson != '' && res.body.receiveAddressJson != null) {
						this.addressList = JSON.parse(res.body.receiveAddressJson);
						if (this.manageType == 'edit') {
							console.log(this.ind);
							this.addressList.splice(this.ind, 1);
							console.log(this.addressList, 99888);
						}
						console.log(this.manageType);
					}
				}
			});
		},
		openPicker() {
		                console.log('执行打开地址选择器')
		                this.show = true
		            },
		
		            changeClick(value, value2, value3){
		
		                console.log('地址选择器 = ' + value + value2 + value3);
		
		                this.province = value;
		                this.city = value2;
		                this.area = value3;
		
		            },
		            onhideShow() {
		                this.show = false
		                console.log('执行了关闭地址选择器')
		            },
		            //选中省市区
		            onsetCity(e) {
						console.log(e);
		                let data = e.detail.target.dataset;
		                let address = data.province + data.city + data.area;
						this.addressData.province=data.province
						this.addressData.city=data.city
						this.addressData.district=data.area
		                this.show = false
		              
		            },
		chooseLocation() {
			let that = this;
			uni.getSetting({
				success: res => {
					console.log(res, 123);
					if (res.authSetting['scope.userLocation']) {
						/* 用户授权成功时走这里 */
						this.chooseLocation1();
					} else if (res.authSetting['scope.userLocation'] === undefined) {
						/* 用户未授权时走这里 */
						console.log('没有授权');

						this.handleOpenSetting();
					} else {
						/* 用户拒绝了授权后走这里 */
						console.log('拒绝了授权 false');
						this.handleOpenSetting();
					}
				}
			});
		},

		//地图选择地址
		chooseLocation1() {
			let self = this;
			uni.chooseLocation({
				success: data => {
					self.addressData.addressName = data.name;
					qqmapsdk.reverseGeocoder({
						location: {
							latitude: data.latitude,
							longitude: data.longitude
						},
						success(qes) {
							let qdata = qes.result;
							self.addressData.province = qdata.ad_info.province;
							self.addressData.city = qdata.ad_info.city;
							self.addressData.district = qdata.ad_info.district;
							self.addressData.address = qdata.address;
							self.addressData.areaCode = qdata.ad_info.adcode;

							self.addressData.latitude = qdata.location.lat;
							self.addressData.longitude = qdata.location.lng;
						}
					});
				},
				fail: function(err) {
					console.log('取消按钮', err);
				}
			});
		},
		handleOpenSetting() {
			uni.showToast({
				icon: 'none',
				duration: 1000,
				title: '请先授权位置信息'
			});
			wx.openSetting({
				success: res => {
					console.log('定位 openSetting', res);
					if (res.authSetting['scope.userLocation']) {
						this.chooseLocation1();
					}
				}
			});
		},
		//提交
		confirm() {
			let data = this.addressData;
			if (data.default == true) {
				this.addressList.forEach(item => {
					item.default = false;
				});
			}
			if (!data.name) {
				uni.showToast({
					icon: 'none',
					title: '请填写收货人姓名'
				});
				return;
			}
			// if (!/(^1[3|4|5|7|8][0-9]{9}$)/.test(data.mobile)) {
			//   uni.showToast({
			//     icon: "none",
			//     title: "请输入正确的手机号码",
			//   });
			//   return;
			// }
			if (!data.address) {
				uni.showToast({
					icon: 'none',
					title: '请填写街道信息'
				});
				return;
			}
			if (!data.houseNumber) {
				uni.showToast({
					icon: 'none',
					title: '请填写门牌号信息'
				});
				return;
			}
			let list = [data];
			let list1 = this.addressList;
			console.log(list1, 99888);
			let list2 = [];
			if (list1.length > 0) {
				list2 = list.concat(list1);
			} else {
				list2 = list;
			}
			console.log(list2);
			let postData = {
				receiveAddressJson: JSON.stringify(list2)
			};
			updateUserInfo(postData).then(res => {
				if (res.code == 200) {
					uni.showToast({
						title: '地址保存成功'
					});
					// self.getAddressList();
					setTimeout(function() {
						uni.navigateBack();
					}, 500);
				} else {
					uni.showToast({
						title: '添加失败',
						duration: 1000,
						icon: 'error'
					});
				}
			});
		}
	}
};
</script>

<style lang="scss">
page {
	background: #f8f8f8;
	padding-top: 16upx;
}

.row {
	display: flex;
	align-items: center;
	position: relative;
	padding: 0 30upx;
	height: 110upx;
	background: #fff;

	.tit {
		flex-shrink: 0;
		width: 140upx;
		font-size: 30upx;
		color: #303133;
	}
	.input {
		flex: 1;
		font-size: 30upx;
		color: #303133;
		
	}
	.icon-shouhuodizhi {
		font-size: 36upx;
		color: #909399;
	}
}
.default-row {
	margin-top: 16upx;
	.tit {
		flex: 1;
	}
	switch {
		transform: translateX(16upx) scale(0.9);
	}
}
.add-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 690upx;
	height: 80upx;
	margin: 60upx auto;
	font-size: 32rpx;
	color: #fff;
	background-color: #ff633d;
	border-radius: 10upx;
	box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
}
</style>
